package interview.springboot.filter;

import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring Boot 添加filter的方法
 * 1. @Bean method Filter
 * 2. FilterRegistrationBean
 * 3. DelegatingFilterProxy 会重复
 * 4. DelegatingFilterProxyRegistrationBean
 */
@Configuration
public class Filters {

    @Bean
    public Filter01 filter01() {
        return new Filter01();
    }

    @Bean
    public Filter04 filter04() {
        return new Filter04();
    }

    public static class Filter01 implements HttpFilterAdapter{
        @Override
        public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Filter01:" + request.getRequestURL());
            chain.doFilter(request,response);
        }
    }
    public static class Filter04 implements HttpFilterAdapter{
        @Override
        public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Filter04:" + request.getRequestURL());
            chain.doFilter(request,response);
        }
    }

    @Bean
    public FilterRegistrationBean filter02(Filter filter01) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter01);
        registration.setName("filter02");
        registration.addUrlPatterns("/hello2");
        return registration;
    }


    @WebFilter(filterName = "filter03", urlPatterns = "/hello3")
    public static class Filter03 implements HttpFilterAdapter {

        @Override
        public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            System.out.println("Filter03:" + request.getRequestURL());
            chain.doFilter(request, response);
        }
    }


    @Bean
    public DelegatingFilterProxy delegatingFilterProxy(){
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetBeanName("filter04");
        return proxy;
    }

    @Bean
    public DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean(){
        DelegatingFilterProxyRegistrationBean proxy = new DelegatingFilterProxyRegistrationBean("filter04");
        proxy.addUrlPatterns("/*");
        return proxy;
    }
}
